<!--
 * @Author: liuzisheng 1171764830@qq.com
 * @Date: 2023-11-17 19:16:25
 * @LastEditors: liuzisheng 1171764830@qq.com
 * @LastEditTime: 2023-11-20 20:22:08
 * @FilePath: /vue3-learn-items/src/views/AboutView.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>This is about</div>
  <div>
    <ClassInfoList />
    <div ref="div">小满Ref: {{ message.name }}</div>
    <hr />
    <div>
      {{ debouncedCount }}
    </div>
    <hr />
    <button @click="onClick">修改 ref</button>
    <button @click="change">修改 customRef</button>
  </div>
</template>

<script setup lang="ts">
/*
  isRef 判断一个东西是否是ref对象
  shallowRef or ref 都可以用来创建一个响应式对象, 
    ref 创建一个响应式对象, 并且返回这个对象, 
    shallowRef 创建一个浅层次的响应式对象, 并且返回这个对象
    ref和shallowRef的区别:
      1. ref创建的对象是响应式的,
        shallowRef创建的对象不是响应式的,
        ref创建的对象可以被.value属性访问,
        shallowRef创建的对象不可以被.value属性访问
      2. ref创建的对象是对象,
        shallowRef创建的对象是对象,
        ref创建的对象是响应式的,
        shallowRef创建的对象不是响应式的
      3. 两个不能在一块使用，会被影响
 
  triggerRef 强制更新页面DOM
*/
import { Ref, onMounted, ref, isRef, shallowRef, triggerRef, customRef } from "vue"
import ClassInfoList from "@/views/class/class.vue"
// let name = ref<number>(0)
// onMounted(() => {
//   console.log(isRef(count))
// })

type Obj = {
  name: string
}
let message: Ref<Obj> = shallowRef({
  name: "小满"
})

function useDebounced<T = any>(value: T) {
  let timer: any = null
  return customRef((track, trigger) => {
    return {
      get() {
        track()
        return value
      },
      set(newValue) {
        console.log(newValue)

        clearTimeout(timer)
        timer = setTimeout(() => {
          value = newValue
          trigger()
        }, 500)
      }
    }
  })
}

const debouncedCount = useDebounced<string>("大哥")

const change = () => {
  debouncedCount.value = "小弟"
}

const onClick = () => {
  message.value.name = "da满"
  triggerRef(message)
}
</script>
<style scoped lang="stylus"></style>
